package com.weixin.common.core.utils;

import com.weixin.common.core.constant.HttpStatus;
import com.weixin.common.core.constant.TokenConstant;
import com.weixin.common.core.exception.BaseException;
import com.weixin.common.core.form.LoginUserDetails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.servlet.http.HttpServletRequest;

/**
 * @version 1.0.0
 * @className: SecurityUtil
 * @description: security权限工具类
 * @author: zhangjunfa
 * @date: 2023/5/30 14:14
 */
public class SecurityUtil {
    /**
     * 获取用户
     **/
    public static LoginUserDetails getLoginUser() {
        try {
            return (LoginUserDetails) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new BaseException(HttpStatus.UNAUTHORIZED, "获取用户信息异常");
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取当前登录用户名
     *
     * @return 当前登录用户名
     */
    public static String getUserName() {
        return getLoginUser().getUsername();
    }

    /**
     * 获取请求token
     */
    public static String getToken()
    {
        return getToken(ServletUtil.getRequest());
    }

    /**
     * 根据request获取请求token
     */
    public static String getToken(HttpServletRequest request)
    {
        // 从header获取token标识
        String token = request.getHeader(TokenConstant.AUTHENTICATION);
        return replaceTokenPrefix(token);
    }

    /**
     * 裁剪token前缀
     */
    public static String replaceTokenPrefix(String token)
    {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstant.PREFIX))
        {
            token = token.replaceFirst(TokenConstant.PREFIX, "");
        }
        return token;
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }
}
